//
//  WPSearchDataManager.m
//  wobingwoyi
//
//  Created by WGP on 16/7/25.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPSearchDataManager.h"

#define  ArrayKey  @"myArray"

@implementation WPSearchDataManager


+(NSArray *)readNSUserDefaults{//取出缓存的数据
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray * myArray = [userDefaultes arrayForKey:ArrayKey];
    return myArray;
}

//缓存搜索数组
+(void)saveSearchText :(NSString *)seaTxt
{
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    //读取数组NSArray类型的数据
    NSArray *myArray = [userDefaultes arrayForKey:ArrayKey];
    if (myArray.count > 0) {//先取出数组，判断是否有值，有值继续添加，无值创建数组
        
    }else{
        myArray = [NSArray array];
    }
    
    // NSArray --> NSMutableArray
    NSMutableArray *searTXT = [myArray mutableCopy];
    
    [myArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if ([obj isEqualToString:seaTxt])
        {
            [searTXT removeObjectAtIndex:idx];
        }
    }];
    
    
    [searTXT addObject:seaTxt];
    if(searTXT.count > 5)
    {
        [searTXT removeObjectAtIndex:0];
    }
    //将上述数据全部存储到NSUserDefaults中
    //        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaultes setObject:searTXT forKey:ArrayKey];
    [userDefaultes synchronize];
}

+(void)removeAllArray{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:ArrayKey];
    [userDefaults synchronize];
}

@end
